package com.card.hwatt.controllers;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.cglib.beans.BeanGenerator;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public abstract class BaseController {

	private static Logger logger = Logger.getLogger(BaseController.class);

	@ExceptionHandler
	public void exception(HttpServletRequest request, Exception e) {
		StringBuilder builder = new StringBuilder();
		builder.append("=======================ERROR============================");
		builder.append("URI : [" + request.getRequestURI() + "]");

		@SuppressWarnings("unchecked")
		Map<String, Object> parameters = request.getParameterMap();
		for (Entry<String, Object> entry : parameters.entrySet()) {
			builder.append("parameter : [" + entry.getKey() + " : "
					+ entry.getValue() + "]");
		}

		builder.append("exception : [" + e.toString() + "]");
		builder.append("========================================================");
		logger.error(builder);
	}

	protected void print(HttpServletRequest request,
			HttpServletResponse response, String name, List<?> list,
			Map<String, Object> params) {
		List<Object> src = new ArrayList<Object>();

		if (CollectionUtils.isNotEmpty(list)) {
			Class<?> cls = list.get(0).getClass();
			BeanGenerator generator = new BeanGenerator();
			for (Field field : cls.getFields()) {
				generator.addProperty(field.getName(), field.getType());
			}

			for (Object obj : list) {
				Object row = generator.create();
				BeanMap beanMap = BeanMap.create(row);
				for (Field field : cls.getFields()) {
					try {
						beanMap.put(field.getName(), field.get(obj));
					} catch (Exception e) {
						logger.error(e);
					}
				}
				src.add(row);
			}
		}

		JRDataSource dataSource = new JRBeanCollectionDataSource(src);

		String realPath = request.getSession().getServletContext()
				.getRealPath("/reports");
		String path = realPath + File.separatorChar + name + ".jasper";
		OutputStream stream = null;
		try {
			byte[] bytes = JasperRunManager.runReportToPdf(path, params,
					dataSource);
			stream = response.getOutputStream();
			stream.write(bytes);
			stream.flush();
			response.setContentType("application/pdf");
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (Exception e) {
				}
			}
		}
	}
}
